<?php
namespace app\admin\service;

use app\model\Admin;
use app\model\Menu;
use app\exception\HttpCode;
use think\facade\Session;

/**
 * Class LoginService
 * @package app\service
 */
class LoginService extends CommonService
{

    /**
     * 登录操作
     * @param $request
     * @return array
     * @throws HttpCode
     */
    public static function login($request)
    {
        $username = $request['username'];
        $password = $request['password'];

        $admin = Admin::getOne(['username' => $username]);


        // 管理员不存在
        if (empty($admin))
        {
            self::error(400, '用户名或者密码错误');
        }

        // 冻结
        if ($admin['status'] != 1)
        {
            self::error(400, '账号被冻结,请联系管理员');
        }

        // 检查密码
        $pwd = self::password($password);
        if ($admin['password'] !== $pwd)
        {
            self::error(400, '用户名或者密码错误');
        }

        // 修改登录时间和IP
        $data = [
            'last_login_time' => time(),
            'last_login_ip' => request()->ip(),
        ];
        Admin::updateOne($data, ['id' => $admin['id']]);

        Session::set('admin', $admin);
        Session::set('admin_id', $admin['id']);
        return self::success();
    }

    /**
     *
     */
    public static function password($pwd)
    {
        return md5(md5($pwd) . 'yl0001');
    }
}